<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询设备使用人员" v-model="deviceUsePersonName"></el-input>
      <el-input style="width: 200px; margin: 0 5px" placeholder="查询设备名称" v-model="deviceName"></el-input>
      <el-input style="width: 200px; margin: 0 5px" placeholder="查询设备编码" v-model="deviceCode"></el-input>
      <el-select
          style="width: 200px; margin: 0 5px"
          placeholder="查询设备类型"
          v-model="deviceType"
          filterable
          clearable
      >
        <el-option
            v-for="item in deviceTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      <el-button type="primary" @click="load(1)">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="info" plain @click="exportData">批量导出</el-button>
      <el-upload :action="$baseUrl + '/OfficeDevices/import'" :headers="{token: user.token}" :on-success="handleImport" style="display: inline-block; margin-left: 10px" :show-file-list="false">
        <el-button type="primary" plain>批量导入</el-button>
      </el-upload>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
<!--      <el-table-column type="index" :index="indexMethod" label="设备号" width="70" align="center"></el-table-column>-->
      <el-table-column prop="id" label="设备序列号" width="140" align="center"></el-table-column>
      <el-table-column label="设备图片" width="80px">
        <template v-slot="scope">
          <div style="display: flex; align-items: center; width: auto">
            <el-image style="width: 50px; height: 50px; border-radius: 50%" v-if="scope.row.devicePhotoUrl" :src="scope.row.devicePhotoUrl" :preview-src-list="[scope.row.devicePhotoUrl]"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="deviceCode" label="设备ID" align="center" width="150">
        <template slot-scope="{ row }">
          <span style="color: #1e90ff;">{{ row.deviceCode }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="deviceType" label="设备类型" align="center"></el-table-column>
            <el-table-column label="设备二维码" width="80px">
        <template v-slot="scope">
          <div style="display: flex; align-items: center; width: auto">
            <el-image style="width: 50px; height: 50px; border-radius: 0%" v-if="scope.row.deviceInfoCode" :src="scope.row.deviceInfoCode" :preview-src-list="[scope.row.deviceInfoCode]"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="deviceName" label="设备名称" align="center"></el-table-column>
      <el-table-column prop="deviceBrand" label="设备品牌" align="center"></el-table-column>
      <el-table-column prop="deviceUsePerson" label="使用人员" align="center"></el-table-column>
      <el-table-column prop="deviceStatus" label="设备状态" align="center" width="100">
        <template v-slot="scope">
          <el-tag :type="getStatusType(scope.row.deviceStatus)">
            {{ scope.row.deviceStatus }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="录入时间" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>

          <el-dropdown>
            <el-button style="margin-top: 4px" size="mini" type="danger" plain>
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleGen(scope.row)">生成二维码</el-dropdown-item>
              <el-dropdown-item @click.native="del(scope.row.id)" class="danger">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="办公设备信息" :visible.sync="fromVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="设备类型" prop="deviceType">
          <el-select
              style="width: 200px; margin: 0 5px"
              placeholder="查询设备类型"
              v-model="form.deviceType"
              filterable
              clearable
          >
            <el-option
                v-for="item in deviceTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
            <el-form-item label="设备编码" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="设备编码"></el-input>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备品牌" prop="deviceBrand">
          <el-input v-model="form.deviceBrand" placeholder="设备品牌"></el-input>
        </el-form-item>
        <el-form-item label="使用人员" prop="DeviceUsePerson">
          <el-select v-model="form.deviceUsePerson" filterable clearable remote :remote-method="searchPerson" @clear="handleClear" placeholder="请输入使用人员">
            <el-option
                v-for="person in persons"
                :key="person.id"
                :label="person.name"
                :value="person.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-select v-model="form.deviceStatus" placeholder="设备状态">
            <el-option label="未分配" value="未分配"></el-option>
            <el-option label="已分配" value="已分配"></el-option>
            <el-option label="已报废" value="已报废"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备图片">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-image
                v-if="form.devicePhotoUrl"
                style="width: 100px; height: 100px; border-radius: 5px;"
                :src="form.devicePhotoUrl"
                fit="cover"
                :preview-src-list="[form.devicePhotoUrl]"
            ></el-image>

            <el-button
                v-if="form.devicePhotoUrl"
                type="success"
                size="mini"
                @click="removeImage"
            >
              删除
            </el-button>
          </div>

          <el-upload
              class="avatar-uploader"
              :action="$baseUrl + '/File/upload'"
              :headers="{ token: user.token }"
              :file-list="form.devicePhotoUrl ? [{ name: '设备图片', url: form.devicePhotoUrl }] : []"
              list-type="picture"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
          >
            <el-button v-if="!form.devicePhotoUrl" type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { format } from 'date-fns';
export default {
  name: "OfficeDevices",
  data() {
    return {
      selectedPerson: null,
      persons: [], // 存储人员信息
      deviceTypeOptions: [],
      tableData: [],  // 所有的数据
      pageNum: 1,     // 当前的页码
      pageSize: 10,   // 每页显示的个数
      deviceName: '',
      deviceCode: '',
      deviceType: '',
      deviceUsePersonName:'',
      total: 0,
      fromVisible: false,
      form: {},
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
      rules: {
        deviceType: [
          { required: true, message: '请选择设备类型', trigger: 'blur' },
        ]
      },
      ids: []
    }
  },
  created() {
    this.load(this.pageNum)
  },
  mounted() {
    this.fetchDeviceTypes();
  },
  methods: {
    fetchDeviceTypes() {
      this.$request.get('/OfficeDevCategory/getAllCategories')
          .then(res => {
            console.log(res)
            if (res.code === '200') {
              this.deviceTypeOptions = res.data;
            }
          })
          .catch(error => {
            console.error('获取设备类型失败', error);
          });
    },
    searchPerson(query){
      if (query.trim()){
        this.$request.get('/User/selectByName', {
          params: {
            userName: query,
          }
        }).then(res => {
          if (res.code === '200') {
            this.persons = res.data
          }else {
            console.error('查询人员时发生错误:', res.msg);
          }
        })
      }else {
        this.persons = []
      }
    },
    // 清空输入框时触发
    handleClear() {
      this.selectedPerson = null; // 清空选中的值
      this.persons = []; // 清空下拉框数据
    },
    getStatusType(status) {
      switch (status) {
        case "已分配":
          return "success"; // 绿色
        case "未分配":
          return "warning"; // 黄色
        case "维修中":
          return "danger"; // 红色
        case "已报废":
          return "info"; // 灰色
        default:
          return ""; // 默认不加颜色
      }
    },
    indexMethod(index){
      return (this.pageNum - 1) * this.pageSize + index + 1;
    },
    handleImport(res, file, fileList) {
      if (res.code === '200') {
        this.$message.success("操作成功")
        this.load(1)
      } else {
        this.$message.error(res.msg)
      }
    },
    removeImage() {
      this.form.devicePhotoUrl = ''; // 清空图片路径
      this.$message.success('图片已删除');
    },
    exportData() {   // 批量导出数据
      this.$message.success("该功能赞暂未开发！")
      return
      // if (!this.ids.length) {   // 没有选择行的时候，全部导出  或者根据我的搜索条件导出
      //   window.open(this.$baseUrl + '/Monitor/export?token=' + this.user.token + "&address="
      //       + this.address + "&type=" + this.type)
      // } else {      // [1,2,3] => '1,2,3'
      //   let idStr = this.ids.join(',')
      //   window.open(this.$baseUrl + '/Monitor/export?token=' + this.user.token + '&ids=' + idStr)
      // }
    },
    migration(){
      this.$request.get('/Monitor/migration').then(res => {
        if(res.code === '200'){
          this.$message.success(res.data)
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    delBatch() {
      this.$message.success("该功能赞暂未开发！")
      return
      // if (!this.ids.length) {
      //   this.$message.warning('请选择数据')
      //   return
      // }
      // this.$confirm('您确认批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
      //   this.$request.delete('/Monitor/delete/batch', { data: this.ids }).then(res => {
      //     if (res.code === '200') {   // 表示操作成功
      //       this.$message.success('操作成功')
      //       this.load(this.pageNum)
      //     } else {
      //       this.$message.error(res.msg)  // 弹出错误的信息
      //     }
      //   })
      // }).catch(() => {})
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },
    del(id) {
      this.$confirm('您确认删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/OfficeDevices/delete/' + id).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(this.pageNum)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {})
    },
    handleGen(row) {   // 生成二维码
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据

      // 确保 guid 正确传递
      console.log(this.form.id); // 打印查看guid是否正确

      // 调用生成二维码的接口
      this.$request.get('/QRCode/generate', {
        params: {
          id: this.form.id // 传递guid参数
        }
      }).then(res => {
        if (res.code === '200') {
          this.form.deviceInfoCode = res.data;
          this.load(this.pageNum);

          this.$message.success('二维码生成成功');
        } else {
          this.$message.error(res.msg);
        }
      }).catch(error => {
        console.error('调用生成二维码接口出错', error);
      });
    },
    handleEdit(row) {   // 生成二维码
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      this.fromVisible = true   // 打开弹窗
    },
    handleAdd() {   // 新增数据
      this.form = {}
      this.fromVisible = true   // 打开弹窗
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? '/OfficeDevices/update': '/OfficeDevices/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.load(this.pageNum)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    reset() {
      this.deviceName = ''
      this.deviceType = ''
      this.deviceUsePersonName = ""
      this.load(this.pageNum)
    },
    load(pageNum) {  // 分页查询
      if (pageNum)  this.pageNum = pageNum
      this.$request.get('/OfficeDevices/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          deviceName: this.deviceName,
          deviceCode: this.deviceCode,
          deviceUsePersonName: this.deviceUsePersonName,
          deviceType: this.deviceType
        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data
        this.tableData = res.data.map(item => {
          item.createTime = format(new Date(item.createTime), 'yyyy-MM-dd');  // 格式化日期
          item.updateTime = format(new Date(item.updateTime), 'yyyy-MM-dd');  // 格式化日期
          return item;
        });
        this.total = res.total
      })
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把user的头像属性换成上传的图片的链接
      this.form.devicePhotoUrl = response.data
    },
  }
}
</script>

<style scoped>

</style>
